// pages/find/find.js

Page({

    /**
     * 页面的初始数据
     */
    data: {
        videoListOne: [], // 视频列表
        videoListTwo: [], //视频列表
        lastId: 922337203685477, // 每次后端来的数据记录最后一条id,默认得足够大
        hasNew: true, // 是否还有新的内容，每次页大小10条，若传来的数据小于10条则没有新的内容了
        refreshStatus: false, // false时关闭下拉刷新
        isLoading: false, // 是否正在加载
    },

    /**
     * 触底事件
     */
    touchBottomHandle(res) {
        if (!this.data.hasNew) {
            return false;
        }
        this.loadVideoList();
    },

    /**
     * 查看视频
     */
    previewVideoClick(res) {
        // 预览视频
        wx.previewMedia({
            sources: [{
                url: res.currentTarget.dataset.video.video,
                type: "video",
                poster: res.currentTarget.dataset.video.image
            }],
            success() {

            },
            fail() {

            }
        })
    },

    // 加载视频列表
    loadVideoList: function() {
        let that = this;
        that.setData({
            isLoading: true
        })
        // 请求后端数据
        wx.fetch({
                url: "/video",
                data: {
                    lastId: that.data.lastId
                }
            })
            .then(res => {
                let tagH1 = 0;
                let tagH2 = 0;
                res.data.videos.forEach((video) => {
                    if (tagH1 <= tagH2) {
                        that.data.videoListOne.push(video);
                        tagH1 += video.height / (video.width / 345) + 96;
                    } else {
                        that.data.videoListTwo.push(video);
                        tagH2 += video.height / (video.width / 345) + 96;
                    }
                    that.data.lastId = video.id;
                });
                that.setData({
                    videoListOne: that.data.videoListOne,
                    videoListTwo: that.data.videoListTwo,
                    hasNew: res.data.videos.length === 10,
                    refreshStatus: false,
                    isLoading: false,
                });
            });
    },

    /**
     * 刷新视频列表
     */
    refreshVideoList() {
        this.setData({
            videoListOne: [],
            videoListTwo: [],
            lastId: 922337203685477,
            hasNew: true,
        });
        this.loadVideoList();
    },

    onLoad: function() {},
    onReady: function() {
        this.refreshVideoList();
    }
})